import { getCache, setCache } from '@/utils';
import { defineStore } from 'pinia';
import { ref } from 'vue';
import { user } from '@/store';
import {bindAuthInfoApi} from "@/api"
const { afterLogin,getUserInfo }  = user()
// const {  } = user();

export const h5Authorization = defineStore('h5Authorization', () => {
    const H5Openid = ref('');

    const authorizedLogin=async () =>{
        if(getCache('userInfo')){
            await getUserInfo()
        }
        
        const code = getQueryString('code');
        if (code) {
            
            const userInfo = getCache('userInfo')
            console.log('code----',code,userInfo.id)
            bindAuthInfoApi({
                code: code,
                userId:userInfo.id
            }).then(async res => {
                // H5Openid.value = res.data.openId;
                // setCache('H5_OPENID', res.data.openId);
                // setCache('H5_UNIONID', res.data.unionId);
                // setCache('token', res.data.token);
                await afterLogin();
            });
        } else {
            console.log('正常进入')
            // setCache('H5_OPENID', 'oz5g76wH2PLF9_KcbU5ztfYp6ySI');
            // setCache('H5_UNIONID', 'oZnpF6aZjben0hSMvbYP4fVKyndc');
            // setCache('token', 'eyJhbGciOiJIUzUxMiJ9.eyJ1c2VySWQiOjE2ODA0MTU3NjUwOTA1OTQ4MTcsImFjY291bnQiOiIxNzY3MTYxNzkwOSIsInV1aWQiOiIzZWZhMThmMC1iOWYzLTQxYTctODkyZC1lNGY5ZDQ4MTVkYjMiLCJjbGllbnRUeXBlRW51bSI6Ik9GRklDSUFMIiwic3ViIjoiMTY4MDQxNTc2NTA5MDU5NDgxNyIsImlhdCI6MTcxNjE4ODU3NiwiZXhwIjoxNzE2NzkzMzc2fQ._1ijks84fNWBmBSPwpFwy8SR7-QOaOJRAO49H63awCxzwIB4kLhdsZPdR61h0PoF5vDzLjIV2CSw9faT0HVkGw');
            // await afterLogin();
    
            // let thisUrl = encodeURIComponent(
            //     `${import.meta.env.VITE_H5_PATH}/#/pages/subpackage/pages/meet/VoucherCenter`,
            // );
            // window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd13aabeb40898e1d&redirect_uri=${thisUrl}&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect`;
        }
    }


    const getQueryString = (name: string) => {
        const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`, 'i');
        const r = window.location.search.substring(1).match(reg);
        if (r !== null) return decodeURI(r[2]);
        return null;
    };

return{
    authorizedLogin
}

})